package com.bolt.admin.module.quartz.service;

import com.bolt.admin.module.email.service.EmailService;
import com.bolt.admin.module.quartz.entity.JobEntity;
import com.bolt.admin.module.quartz.entity.JobLogEntity;
import com.bolt.common.io.resource.ResourceMode;
import com.bolt.common.utils.ExceptionUtil;
import com.bolt.common.utils.SpringContextUtil;
import com.bolt.support.freemarker.FreeMarkerEngine;
import com.bolt.support.freemarker.Template;
import com.bolt.support.freemarker.TemplateConfig;
import io.netty.util.internal.ThrowableUtil;
import org.quartz.JobExecutionContext;
import org.quartz.Trigger;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2020/10/10.
 */
public class ExecutionJobBean extends QuartzJobBean {
    @Override
    public void executeInternal(JobExecutionContext context) {
        JobEntity quartzJob = (JobEntity) context.getMergedJobDataMap().get(JobEntity.JOB_KEY);
        JobLogService jobLogService = SpringContextUtil.getBean(JobLogService.class);
        JobService jobService = SpringContextUtil.getBean(JobService.class);
        JobLogEntity logEntity = new JobLogEntity();
        logEntity.setJobName(quartzJob.getJobName());
        logEntity.setBeanName(quartzJob.getBeanName());
        logEntity.setMethodName(quartzJob.getMethodName());
        logEntity.setParams(quartzJob.getParams());
        long startTime = System.currentTimeMillis();
        Trigger trigger = context.getTrigger();
        try {
            QuartzTask task = new QuartzTask(quartzJob.getBeanName(), quartzJob.getMethodName(),
                    quartzJob.getParams());
            task.call();

            long times = System.currentTimeMillis() - startTime;
            logEntity.setTime(times);
            logEntity.setIsSuccess(true);
            logEntity.setFireTime(new java.util.Date());
            logEntity.setPreviousFireTime(trigger.getPreviousFireTime());
            logEntity.setNextFireTime(trigger.getNextFireTime());
            logEntity.setFireCount(new Integer(context.getRefireCount()));

        } catch (Exception ex) {
            long times = System.currentTimeMillis() - startTime;
            logEntity.setTime(times);
            // 任务状态 0：成功 1：失败
            logEntity.setIsSuccess(false);
            logEntity.setExceptionDetail(ExceptionUtil.getMessage(ex));
            if (quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()) {
                quartzJob.setIsPause(false);
                //更新状态
                jobService.updateIsPause(quartzJob);
            }
            if (quartzJob.getEmail() != null) {
                EmailService emailService = SpringContextUtil.getBean(EmailService.class);
                // 邮箱报警
                String subject = "定时任务【" + quartzJob.getJobName() + "】执行失败，请尽快处理！";
                String mailText = taskAlarm(quartzJob, ThrowableUtil.stackTraceToString(ex));
                emailService.send(quartzJob.getEmail(), subject, mailText);
            }
        } finally {
            jobLogService.save(logEntity);
        }
    }

    private String taskAlarm(JobEntity quartzJob, String msg) {
        Map <String, Object> data = new HashMap <>(16);
        data.put("task", quartzJob);
        data.put("msg", msg);
        FreeMarkerEngine engine = new FreeMarkerEngine(new TemplateConfig("email_templates", ResourceMode.CLASSPATH));
        Template template = engine.getTemplate("email/taskAlarm.ftl");
        return template.render(data);
    }
}

 